package com.pvj.myaccount.ui.slideshow

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pvj.myaccount.repository.MonthCostRepository
import com.pvj.myaccount.room.entity.MonthCost
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MonthCostViewModel : ViewModel() {
    private val repository = MonthCostRepository()

    private val _listMonthCost = MutableLiveData<List<MonthCost>?>()

    val listMonthCost: LiveData<List<MonthCost>?> = _listMonthCost

    fun loadDataAsync() {
        viewModelScope.launch(Dispatchers.IO) {
            val data = repository.getAll()
            // 更新LiveData
            if (data == null) {
                _listMonthCost.postValue(listOf<MonthCost>())
            } else {
                _listMonthCost.postValue(data)
            }
        }
    }

    fun insertAsync(monthCost: MonthCost) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.insert(monthCost)
        }
    }

    fun delete(monthCost: MonthCost) {
        repository.delete(monthCost)
    }

    fun updateAsync(monthCost: MonthCost) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.update(monthCost)
        }
    }

}